package com.lagou.homework.component;

import com.lagou.homework.api.UserService;
import com.lagou.homework.utils.TPMonitor;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.*;

/**
 * @author 皮卡小丘丘 2021/2/24
 */
@Component
public class ConsumerRunner{

    //线程池，用于调用runner
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    @Reference
    UserService userService;

    private int count=0;

    public void start(String msg) throws InterruptedException, ExecutionException {
        Method[] methods = userService.getClass().getMethods();
        TPMonitor.startMonitor(methods,5,5);
        //每25毫秒，轮流执行调用
        while (true){
            String result="";
            switch (count%3){
                case 0:
                    result = (String)executorService.submit(new RunnerA(msg)).get();
                    break;
                case 1:
                    result = (String)executorService.submit(new RunnerB(msg)).get();
                    break;
                case 2:
                    result = (String)executorService.submit(new RunnerC(msg)).get();
            }
            count++;
            //System.out.println(count+result);
            Thread.sleep(25);
        }
    }

    private class RunnerA implements Callable {
        String msg;
        public RunnerA(String msg) {
            this.msg=msg;
        }

        @Override
        public Object call() throws Exception {
            return userService.methodA(msg);
        }
    }

    private class RunnerB implements Callable {
        String msg;
        public RunnerB(String msg) {
            this.msg=msg;
        }

        @Override
        public Object call() throws Exception {
            return userService.methodB(msg);
        }
    }

    private class RunnerC implements Callable {
        String msg;
        public RunnerC(String msg) {
            this.msg=msg;
        }

        @Override
        public Object call() throws Exception {
            return userService.methodC(msg);
        }
    }
}
